﻿using System;
using UnityEngine;

namespace Gp.Scripts.Equip {
    public class ArmorFragmentEntity {
        public bool IsBroken => CurDurabilityRate <= 0.001;
        public bool IsUnDamaged => CurDurabilityRate >= 1 - 0.001;

        // 护甲的总护甲值相当于角色的韧性调整值*20
        // 护甲板最大耐久为总护甲值 / 护甲板数
        public Func<int> FullValue { get; }

        public bool IsShieldFragment { get; }


        public EventHandler OnDurabilityChanged;
        
        public IArmorProvider Provider { get; }

        public int CurDurability {
            get => Mathf.RoundToInt(FullValue() * CurDurabilityRate);
        }

        private float _curDurabilityRate;

        public float CurDurabilityRate {
            get => _curDurabilityRate;
            private set {
                _curDurabilityRate = Mathf.Clamp01(value);
                OnDurabilityChanged?.Invoke(this, null);
            }
        }

        
        public ArmorFragmentEntity(IArmorProvider provider, Func<int> fullValue, float durabilityRate, bool isShieldFragment = false) {
            FullValue = fullValue;
            Provider = provider;

            CurDurabilityRate = durabilityRate;
            IsShieldFragment = isShieldFragment;
        }


        public void Damage(int damage) {
            CurDurabilityRate -= damage / (float) FullValue();
        }


        public void Repair() {
            CurDurabilityRate = 1;
        }

        public void Repair(int amount) {
            CurDurabilityRate += amount / (float)FullValue();
        }

        
        public void Repair(float percent) {
            CurDurabilityRate += percent;
        }
    }
}